package com.shuaiche.yeguan.ui.share;

import android.Manifest;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.shuaiche.yeguan.R;
import com.shuaiche.yeguan.config.HttpUrl;
import com.shuaiche.yeguan.config.SCUserInfoConfig;
import com.shuaiche.yeguan.model.BaseResponseModel;
import com.shuaiche.yeguan.model.SCMultiShareSelectModel;
import com.shuaiche.yeguan.model.ShareObj;
import com.shuaiche.yeguan.net.http.HttpCallBack;
import com.shuaiche.yeguan.net.http.HttpHelper;
import com.shuaiche.yeguan.ui.contract.UploadContractActivity;
import com.shuaiche.yeguan.util.BitmapUtil;
import com.shuaiche.yeguan.util.LogUtils;
import com.shuaiche.yeguan.util.SCQRCodeUtil;
import com.shuaiche.yeguan.util.SCSavePictureListener;
import com.shuaiche.yeguan.util.SCSavePictureUtils;
import com.shuaiche.yeguan.util.ToastShowUtils;
import com.shuaiche.yeguan.util.base64.Base64Utils;
import com.shuaiche.yeguan.util.permission.MPermission;
import com.shuaiche.yeguan.views.dialog.PermissionDialog;
import com.shuaiche.yeguan.views.dialog.ShareContentDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MultiShareSelectActivity extends AppCompatActivity implements View.OnClickListener {
    private static final int BASIC_PERMISSION_REQUEST_CODE_FOR_CAMERA = 1002;

    private static final int REQUEST_CODE_CAMERA = 103;      //选择图片
    private static final int REQUEST_CODE_PREVIEW = 104;     //预览图片
    private static final int REQUEST_CODE_MULTI_SHARE = 105;    //多图分享

    private ArrayList<String> carPictures = new ArrayList<>();      //所有的图片
    private ArrayList<String> localPictures = new ArrayList<>();    //本地的图片
    private ArrayList<SCMultiShareSelectModel> multiShares;

    private RecyclerView rvCarPics;
    private Button btnSaveShare;        //一键分享
    private Bitmap qrCodeBitmap;    //分享二维码

    private final String[] BASIC_PERMISSIONS = new String[]{
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
    };

    /**
     * 二维码地址
     */
    private String zxingUrl;
    /**
     * 多图分享文案
     */
    private String content;

    private String bizType = "carPic";         //分享类型 多图分享
    private Long dataMerchantId;    //车所属商户id
    private String bizData;         //车辆id 或 条件
    private JSONObject paramsJson;

    /**
     * app中定制的loadigview
     */
//    private DefaultLoadingView loadingView;

    private SCMultiCarPicsSelectAdapter adapter;

    private View zxingView;
    private View rootView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

        setContentView(R.layout.activity_multi_share_select);

        initViews();
    }

    private void initViews() {
        initFindViews();

        getData();
    }

    private void initFindViews() {
        multiShares = new ArrayList<>();
        btnSaveShare = (Button) findViewById(R.id.btnSaveShare);
        btnSaveShare.setOnClickListener(this);


        rvCarPics = (RecyclerView) findViewById(R.id.rvCarPics);
        GridLayoutManager layoutManager = new GridLayoutManager(this, 4);
        rvCarPics.setLayoutManager(layoutManager);
    }

    private void getData() {
        if (getIntent() != null) {

            ShareObj shareObj = (ShareObj) getIntent().getSerializableExtra("shareObj");
            zxingUrl = shareObj.getShareUrl();
            content = shareObj.getMultiContent();
            bizData = shareObj.getBizData();
            dataMerchantId = shareObj.getDataMerchantId();
            paramsJson = shareObj.getParamsJson();
            bizType = shareObj.getBizType() == null ? "carPic" : shareObj.getBizType();
            /**
             * 二维码图
             */
            zxingView = LayoutInflater.from(this)
                    .inflate(R.layout.sc_dlg_car_list_qrcode,
                            null);
            rootView = zxingView.findViewById(R.id.vRoot);

            final ImageView zxing = zxingView.findViewById(R.id.ivQRCode);
            TextView tvCompany = zxingView.findViewById(R.id.tvTitle);
            TextView tvDescription = zxingView.findViewById(R.id.tvDescription);
            /**
             * 多车辆分享
             */
            if (dataMerchantId == null) {
                tvDescription.setText("长按查看车辆列表");
            } else {
                //多图分享
                tvDescription.setText("长按查看车辆详情");
            }

            if (SCUserInfoConfig.isRegisterMerchant()) {
                tvCompany.setVisibility(View.VISIBLE);
                tvCompany.setText(SCUserInfoConfig.getUserinfo().getMerchantName());
            } else {
                tvCompany.setVisibility(View.GONE);
            }

            /**多图地址*/
            ArrayList<String> argus = (ArrayList<String>) shareObj.getPicUrls();
            for (String model : argus) {
                carPictures.add(model);
                multiShares.add(new SCMultiShareSelectModel(model, true, false));
            }


            if (carPictures.size() >= 5) {
                /**
                 * 缓存二维码
                 */
                carPictures.add(4, "sccache");
                multiShares.add(4, new SCMultiShareSelectModel("sccache", true, false));
            } else {
                /**
                 * 缓存二维码
                 */
                carPictures.add("sccache");
                multiShares.add(new SCMultiShareSelectModel("sccache", true, false));
            }

            /**
             * 默认选中前9张
             */
            if (multiShares.size() > 9) {
                for (int i = 9; i < multiShares.size(); i++) {
                    multiShares.get(i).setSelect(false);
                }
            }

            final StringBuffer shareUrl = new StringBuffer(zxingUrl);
            if (paramsJson != null) {
                if (SCUserInfoConfig.isLogin()) {
                    paramsJson.put("shareUserId", SCUserInfoConfig.getUserinfo().getUserId());
                }
                if (SCUserInfoConfig.isRegisterMerchant()) {
                    paramsJson.put("shareMerchantId", SCUserInfoConfig.getUserinfo().getMerchantId());
                }

            } else {
                paramsJson = new JSONObject();
                if (SCUserInfoConfig.isLogin()) {
                    paramsJson.put("shareUserId", SCUserInfoConfig.getUserinfo().getUserId());
                }
                if (SCUserInfoConfig.isRegisterMerchant()) {
                    paramsJson.put("shareMerchantId", SCUserInfoConfig.getUserinfo().getMerchantId());
                }
            }
            shareUrl.append("?params=" + Base64Utils.encodeToString(paramsJson.toJSONString().getBytes()));

            Map<String,Object> maps = new HashMap<>();
            maps.put("token","Yba2F30PE9");
            maps.put("original",shareUrl.toString());
            HttpHelper.getInstance().url(HttpUrl.SCDWZ).addJsonParam(maps).jsonPost(new HttpCallBack<BaseResponseModel>(this) {
                @Override
                public void onSuccessed(BaseResponseModel result) {
                    String shareUrl = (String) result.getData();
                    Bitmap bitmap = SCQRCodeUtil.createQRCodeBitmap(shareUrl, 480, 480);
                    zxing.setImageBitmap(bitmap);
                    qrCodeBitmap = BitmapUtil.loadBitmapFromView(rootView);
                    loadAdapter();
                }

                @Override
                public void onFailured(String errorCode, String errMsg) {
                    Bitmap bitmap = SCQRCodeUtil.createQRCodeBitmap(shareUrl.toString(), 480, 480);
                    zxing.setImageBitmap(bitmap);
                    qrCodeBitmap = BitmapUtil.loadBitmapFromView(rootView);
                    loadAdapter();
                }
            });

        }
    }

    private void loadAdapter() {
        if (multiShares != null && multiShares.size() > 0) {
            for (int j = 0; j < multiShares.size(); j++) {
                if ("".equals(multiShares.get(j).getUrl())) {
                    multiShares.remove(j);
                }
            }
        }
        LogUtils.log("multiShares",multiShares.toString());
        adapter = new SCMultiCarPicsSelectAdapter(this, multiShares, qrCodeBitmap);
        rvCarPics.setAdapter(adapter);

        adapter.setCallbackListener(new SCMultiCarPicsSelectAdapter.CallbackListener() {
            @Override
            public void itemClick(int position) {
                int type = adapter.getItemViewType(position);
                /**
                 * 设置选中与否
                 */
                multiShares.get(position).setSelect(!multiShares.get(position).isSelect());
                int i = 0;
                for (SCMultiShareSelectModel model : multiShares) {
                    if (model.isSelect()) {
                        i++;
                    }
                }
                if (i > 9) {
                    ToastShowUtils.showTipToast("最多选择9张图片");
                    multiShares.get(position).setSelect(false);
                }
                adapter.notifyDataSetChanged();
            }
        });

//        loadingView.loadSuccess(0, null);
        btnSaveShare.setVisibility(View.VISIBLE);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_back:
                finish();
                break;
            case R.id.btnSaveShare:
                if (ContextCompat.checkSelfPermission(this,Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

                    PermissionDialog dialog = new PermissionDialog(this,"申请文件读写存储权限","申请文件读写存储权限，用于选择上传媒体图片");
                    dialog.setOnPermissionResultListener(new PermissionDialog.OnPermissionResultListener() {
                        @Override
                        public void onConfirm() {
                            MPermission.with(MultiShareSelectActivity.this)
                                    .setRequestCode(BASIC_PERMISSION_REQUEST_CODE_FOR_CAMERA)
                                    .permissions(BASIC_PERMISSIONS)
                                    .request();
                            dialog.dismiss();
                        }

                        @Override
                        public void onRefuse() {

                        }
                    });
                    dialog.setCancelable(false);
                    dialog.show();



                }else {
                    savePic();
                }

                break;
        }
    }

    /**
     * 保存图片
     */
    private List<String> savePics = new ArrayList<>();

    private void savePic() {
        savePics.clear();
        for (int i = 0; i < multiShares.size(); i++) {
            if (multiShares.get(i).isSelect()) {
                savePics.add(multiShares.get(i).getUrl());
            }

        }

        if (savePics.size() == 0) {
            ToastShowUtils.showTipToast("请选择车辆图片");
            return;
        }

        Toast.makeText(this, "图片下载中，请稍后...", Toast.LENGTH_LONG).show();

        SCSavePictureUtils.getInstance().saveImage(
                MultiShareSelectActivity.this,
                savePics,
                qrCodeBitmap,
                new SCSavePictureListener() {
                    @Override
                    public void onFinish() {
                        if (SCUserInfoConfig.isRegisterMerchant()) {
                            openShareContentDialog();
                        } else {
                            openWeixin();
                        }
                    }
                });
    }

    private void openShareContentDialog() {
        ShareContentDialog dialog = new ShareContentDialog(this,"分享",content);
        dialog.setOnPermissionResultListener(new ShareContentDialog.OnPermissionResultListener() {
            @Override
            public void onConfirm() {
                ClipboardManager cm = (ClipboardManager) MultiShareSelectActivity.this
                        .getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData mClipData = ClipData.newPlainText("Label", content);
                cm.setPrimaryClip(mClipData);
                openWeixin();
            }

            @Override
            public void onRefuse() {

            }
        });
        dialog.setCancelable(false);
        dialog.show();
    }


    /**
     * 多图分享打开微信
     */
    private void openWeixin() {
        Intent intent = new Intent();
        ComponentName cmp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");
        intent.setAction(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setComponent(cmp);
        startActivity(intent);
    }
}